package cc.ufinity.networkdiagnose.widget;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.net.nntp.NewGroupsOrNewsQuery;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.wifi.WifiInfo;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.Account;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.HttpTestManager;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.PullTaskParser;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TaskParser;
import cc.ufinity.networkdiagnose.manager.TelManager;
import cc.ufinity.networkdiagnose.manager.WebAuthManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.HttpUtils;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;

public class TaskWidget extends GeneralTestWidget {
	public final static String PREFS_NAME = "mymobile";
    public final static String PREFS_KEY = "number";
	
	private Activity ctx;
	private TaskParser taskParser;
	private static String TAG = "TaskWidget";
	private ListView taskListView;
	private List<Task> tasks = null;
	private TelManager tm;
	private Handler handler;
	private String myPhoneNumber;
	private WlanManager wlanManager;
	private List<Map<String, Object>> datas;
	public boolean webAuth = false;
	public boolean cmccAuth = false;
	public HttpTestManager httpTestManager;
	private String serverUrl = "";
	public Dialog dialog;
	
	private String networkType;
	
	public TaskWidget(Activity context) { 
		super(context);
		this.ctx = context;

		inflate(context, R.layout.task_widget, this);
		taskListView = (ListView) this.findViewById(R.id.taskListView);
		taskListView.setOnItemClickListener(new OnItemClickListener() {

			@SuppressWarnings("unchecked")
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				GlobalApp.taskOtherList.clear();
				GlobalApp.index = 0;
				
				Map<String, Object> r = (Map<String, Object>) taskListView
						.getAdapter().getItem(position);
				Task task = (Task) r.get("task");
				
				boolean canGO = true;
				if (task.selNetType == ConnectivityManager.TYPE_WIFI) {
					/*if(!isAccountSaved()) {
						return;
					}*/
					if(GlobalApp.DEBUG) {
						initWLAN(task);
					} else {
						networkType = tm.getNetworkType();
			        	if(networkType.equals("UNKNOW"))  {
			        		//未知网络
			        		canGO = false;
			        		showMessage(getContext(), "数据网络未知，请更正网络");
			        	} else if(networkType.equals("HSDPA")
			        			|| networkType.equals("EDGE") 
			        			|| networkType.equals("GPRS"))  {
			        		//移动网络
			        		initWLAN(task);
			        	}else {
			        		//其他网络
			        		canGO = false;
			        		showMessage(getContext(), "手机数据网络不符合测试条件");
			        	}
					}
				} else if(task.selNetType == ConnectivityManager.TYPE_MOBILE_MMS) {
					if(GlobalApp.DEBUG) {
						if(tm.getNetworkType()!=null && tm.getNetworkType().equals("EDGE")) {
							canGO = false;
							showAlertDialog(ctx,"当前网络类型为GSM模式，进行TD测试请先切换至TD网络类型.");
						} else {
							GlobalApp.isWlanFirst = false;
							GlobalApp.taskTD = task;
							wlanManager.closeWifi();
							wlanManager.setMobileDataEnabled(ctx,true);
						}
					} else {
						networkType = tm.getNetworkType();
			        	if(networkType.equals("UNKNOW"))  {
			        		//未知网络
			        		canGO = false;
			        		showMessage(getContext(), "网络未知，请更正网络");
			        	} else if(networkType.equals("HSDPA"))  {
			        		//TD网络
			        		GlobalApp.isWlanFirst = false;
							GlobalApp.taskTD = task;
							wlanManager.closeWifi();
							wlanManager.setMobileDataEnabled(ctx,true);
			        	} else if(networkType.equals("EDGE") || networkType.equals("GPRS"))  {
			        		//GSM网络
			        		canGO = false;
			        		showAlertDialog(ctx,"当前网络类型为GSM模式，进行TD测试请先切换至TD网络类型.");
			        	} else {
			        		//其他网络
			        		canGO = false;
			        		showMessage(getContext(), "当前不在TD网络，无法测试");
			        	}
					}
				} else if(task.selNetType == ConnectivityManager.TYPE_MOBILE) {
					if(GlobalApp.DEBUG) {
						if(tm.getNetworkType()!=null && tm.getNetworkType().equals("HSDPA")) {
							canGO = false;
							showAlertDialog(ctx,"当前网络类型为TD模式，进行GSM测试请先切换至GSM网络类型.");
						} else {
							GlobalApp.isWlanFirst = false;
							GlobalApp.taskGSM = task;
							wlanManager.closeWifi();
							wlanManager.setMobileDataEnabled(ctx,true);
						}
					} else {
						networkType = tm.getNetworkType();
			        	if(networkType.equals("UNKNOW"))  {
			        		//未知网络
			        		canGO = false;
			        		showMessage(getContext(), "网络未知，请更正网络");
			        	} else if(networkType.equals("HSDPA"))  {
			        		//TD网络
			        		canGO = false;
			        		showAlertDialog(ctx,"当前网络类型为TD模式，进行GSM测试请先切换至GSM网络类型.");
			        	} else if(networkType.equals("EDGE") || networkType.equals("GPRS"))  {
			        		//GSM网络
			        		GlobalApp.isWlanFirst = false;
							GlobalApp.taskGSM = task;
							wlanManager.closeWifi();
							wlanManager.setMobileDataEnabled(ctx,true);
			        	} else {
			        		//其他网络
			        		canGO = false;
			        		showMessage(getContext(), "当前不在GSM网络，无法测试");
			        	}
					}
				}
				
				if(canGO) {
					ctx.getIntent().putExtra(TAG_REFER_TASK, task);
					ctx.getIntent().putExtra("TAG_CHECK_TASK", "checkTask"); 
					TaskDetailWidget tdw = new TaskDetailWidget(ctx);
	 	            ctx.setContentView(tdw);
				}
			}

		});

		handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MessageWhat.WIFI_SUCESS_CONNECTED:
					dismissMessageDialog(); 
					start2();
					break;
				case MessageWhat.WIFI_CONNECT_TIMEOUT:
					dismissMessageDialog();
					start2();
//					showMessage(ctx, "连接网络失败");
					break;
				case MessageWhat.TASK_LIST_LOADED_SUCCESS:
					init();
					dismissMessageDialog();
					break;
				case MessageWhat.TASK_LIST_LOADED_FAILED:
					dismissMessageDialog();
					showMessage(ctx, "获取任务列表失败.");
					break;
				case 2:
					showMessage(ctx, "本机手机号码无法获取.");
					dismissMessageDialog();
					break;
				}
			}
		}; 
//		serverUrl = ctx.getResources().getString(R.string.server_url);
		SharedPreferences settings1 = ctx.getSharedPreferences(GlobalApp.CFG_SERVER, 0);
        String ip = settings1.getString(GlobalApp.CFG_SERVER_IP, "");
        String port = settings1.getString(GlobalApp.CFG_SERVER_PORT, "");
        if (ip == null || ip.equals("") || port == null || port.equals("")) {
			showMessage(ctx, "请配置服务器地址！");
		}else {
			serverUrl = "http://" +ip+":"+port;
		}
        httpTestManager = new HttpTestManager(ctx);
		wlanManager = new WlanManager(ctx);
		wlanManager.setHandler(handler);
		tm = new TelManager(ctx);
		tm.setHandler(handler);
 
	}
	
	private void initWLAN(Task task) {
		GlobalApp.isWlanFirst = true;
		GlobalApp.TDorGSM_task = "";
		GlobalApp.taskWlan = task;
		
		GlobalApp.taskTD = new Task();
		GlobalApp.taskTD.id = task.id;
		GlobalApp.taskTD.httpTasks = task.httpTasks;
		GlobalApp.taskTD.ftpTasks = task.ftpTasks;
		GlobalApp.taskTD.pingTasks = task.pingTasks;
		GlobalApp.taskTD.testCount = task.testCount;
		GlobalApp.taskTD.taskType = task.taskType;
		GlobalApp.taskTD.selNetType = ConnectivityManager.TYPE_MOBILE_MMS;
		
		GlobalApp.taskGSM = new Task();
		GlobalApp.taskGSM.id = task.id;
		GlobalApp.taskGSM.httpTasks = task.httpTasks;
		GlobalApp.taskGSM.ftpTasks = task.ftpTasks;
		GlobalApp.taskGSM.pingTasks = task.pingTasks;
		GlobalApp.taskGSM.testCount = task.testCount;
		GlobalApp.taskGSM.taskType = task.taskType;
		GlobalApp.taskGSM.selNetType = ConnectivityManager.TYPE_MOBILE;
		
		wlanManager.setMobileDataEnabled(ctx,false);
	}

	public void start(){
		SharedPreferences settings1 = ctx.getSharedPreferences(GlobalApp.CFG_SERVER, 0);
        String ip = settings1.getString(GlobalApp.CFG_SERVER_IP, "");
        String port = settings1.getString(GlobalApp.CFG_SERVER_PORT, "");
        if (ip == null || ip.equals("") || port == null || port.equals("")) {
			showMessage(ctx, "请配置服务器地址！");
			return;
		}else {
			serverUrl = "http://"+ ip +":"+port;
		}
		WifiInfo wifiInfo = wlanManager.getCurrentNetwork();
		System.err.println(wifiInfo.getSSID()+"==================================SSID");
		if(wifiInfo!=null && wifiInfo.getSSID()!= null &&wifiInfo.getSSID().equals(WlanManager.SSID_CMCC) && !cmccAuth){
			this.showMessageDialog(ctx, "正在认证CMCC网络...");
			cmccAuth = true;
			new Thread(){
				public void run(){
					String  defaultUrl = ctx.getResources().getString(R.string.default_url);
					int httpTestResult = httpTestManager.httpTestNetwork(defaultUrl,1);
				///	if(httpTestResult <= 0)
					//{
						if(!webAuth){
							WebAuthManager wManager = new WebAuthManager(ctx);
							webAuth = true;
					        DBManager db = new DBManager(ctx);
							Account config = db.getAccount();
							String userName ="",pwd=""; 
							if(null != config){ 
								userName = config.userName;
								pwd = config.password;
								if(wManager.auth(defaultUrl, userName, pwd))
									wlanManager.sendMsg(MessageWhat.WIFI_SUCESS_CONNECTED);
								else {
									wlanManager.sendMsg(MessageWhat.WIFI_CONNECT_TIMEOUT);
								}
							}else {
								wlanManager.sendMsg(MessageWhat.WIFI_CONNECT_TIMEOUT);
	  						}
							db.release();
					//	}
					}else {
						wlanManager.sendMsg(MessageWhat.WIFI_SUCESS_CONNECTED);
					}
				}
			}.start();
		}else {
			wlanManager.sendMsg(MessageWhat.WIFI_SUCESS_CONNECTED);
		}
	}
	public void start2() { 
		if (NetworkManager.detectNetworkConnectivity(ctx) == -1) {
			showMessage(ctx, "请连接网络");
			return;
		}
		myPhoneNumber = tm.getPhoneNumber();
		
		if (StringUtils.isEmpty(myPhoneNumber)) {
			showMessage(ctx, "获取本机号码失败,请输入.");
			showInputDialog();
			return;
		} else {
			loadTaskList();
		}
	}

	private void showInputDialog() {
		LayoutInflater factory = LayoutInflater.from(ctx);
		final View dialogView = factory.inflate(
				R.layout.input_phone_num_dialog, null);
		final EditText inputText = (EditText) dialogView
				.findViewById(R.id.phoneNumEditText);
		final AlertDialog.Builder  inputBuilder = new AlertDialog.Builder(ctx);
		inputBuilder.setTitle("提示");
		//inputBuilder.setIcon(R.drawable.smile);
		inputBuilder.setView(dialogView);
		inputBuilder.setPositiveButton("确定",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog1, int which) {
						if (StringUtils.isEmpty(inputText.getText().toString())) {
							try {
								Field field = dialog.getClass().getSuperclass()
										.getDeclaredField("mShowing");
								field.setAccessible(true);
								field.set(dialog, false);
							} catch (Exception e) {
								e.printStackTrace();
							}
							System.out.println("queding ----------------------");
							System.out.println("dialog1" + dialog1);
							showMessage(ctx, "请输入本机号码");
						} else {
							try {
								Field field = dialog.getClass().getSuperclass()
										.getDeclaredField("mShowing");
								field.setAccessible(true);
								field.set(dialog, true);
							} catch (Exception e) {
								e.printStackTrace();
							}
							myPhoneNumber = inputText.getText().toString();
							SharedPreferences settings = ctx.getSharedPreferences(PREFS_NAME, 0);
				            SharedPreferences.Editor editor = settings.edit();
				            editor.putString(PREFS_KEY, myPhoneNumber);
				            editor.commit();   //保存手机号码
				            
							dialog.cancel();
							loadTaskList();
						}
					}
				});
		inputBuilder.setNegativeButton("取消", 
				new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog1, int which) {
				try {
					Field field = dialog.getClass().getSuperclass()
							.getDeclaredField("mShowing");
					field.setAccessible(true);
					field.set(dialog, true);
				} catch (Exception e) {
					e.printStackTrace();
				}
				System.out.println("dialog1" + dialog1);
				dialog.cancel();
			}
		});
		
		dialog = inputBuilder.create();
		dialog.show();
	}

	private void loadTaskList() {
		this.showMessageDialog(ctx, "正在加载任务列表...");
		new Thread() {
			public void run() {
				getTasks();
			}
		}.start();
	}

	private void init() {

		SimpleAdapter adapter = new SimpleAdapter(ctx, datas, R.layout.task_list_widget, 
				new String[] { "taskName", "apName", "taskType","taskNetType" , "taskDesc","taskApnum"}, //名称、热点、类型、描述
				new int[] { R.id.task_name, R.id.ap_name, R.id.task_type ,R.id.task_netType, R.id.task_desc,R.id.task_apnum }); 
		taskListView.setAdapter(adapter);
	}
	
	 
	 private List<Map<String, Object>> getTasks() {
		List<Map<String, Object>> res = new ArrayList<Map<String, Object>>();
		taskParser = new PullTaskParser();
		String labelTaskName = this.getResources().getString(
				R.string.label_task_name);
		String labelTaskType = this.getResources().getString(
				R.string.label_task_type);
		String labelTaskDesc = this.getResources().getString(
				R.string.label_task_desc);
		String labelApName = this.getResources().getString(
				R.string.label_apname);
		String labelApNum = this.getResources().getString(
				R.string.label_task_apnum);
		String labelNetType = this.getResources().getString(R.string.label_task_net);
		// String path = "cc/ufinity/networkdiagnose/widget/tasks.xml";
		//String url = serverUrl +"/Task/ReturnXML.aspx";
		String url = serverUrl +"/wirelessnet/Task/ReturnXML.jsp";
		Log.d("Task", "my phone number is:" + myPhoneNumber);
		myPhoneNumber = tm.getPhoneNumber();
        String requrl = url + "?TaskPhone=" + myPhoneNumber;
		// String requrl = url + "?TaskPhone=13637050391";
		try {
			InputStream is = HttpUtils.getInputStream(requrl);
			tasks = taskParser.parse(is);
			Map<String, Object> t = null;
			for (Task task : tasks) {
				List<Map<String, String[]>> apList = task.apList;
				int apNum = apList!=null?apList.size():0;
				int testedApNum = GlobalApp.getTestedApBumById(task.id);
				String tempString ="";
				if (task!=null && (task.selNetType== ConnectivityManager.TYPE_MOBILE || task.selNetType== ConnectivityManager.TYPE_MOBILE_MMS)) {
					tempString = "已测试次数（单位：次）："+task.testTaskCount;
				}else {
					tempString = "已完成测试AP/待测试AP(单位：个)："+task.testApCount+"/"+apNum;
				}
				t = new HashMap<String, Object>();
				System.out.println("Task的截止时间是-------------"+task.toString());
				t.put("taskName", labelTaskName + task.taskName);
				t.put("apName", labelApName + task.apName);
				t.put("taskType", labelTaskType + task.taskType);
				t.put("taskNetType", labelNetType + task.netType2+"网络");
				t.put("taskDesc", labelTaskDesc + task.taskDes);
				t.put("taskApnum", labelApNum +tempString);
				t.put("task", task);
				res.add(t);
			}
			datas = res;
			Message e = new Message();
			e.what = MessageWhat.TASK_LIST_LOADED_SUCCESS;
			handler.sendMessage(e);
		} catch (Exception e) {
			Log.e(TAG, "解析XML任务时出错：", e);
			Message e1 = new Message();
			e1.what = MessageWhat.TASK_LIST_LOADED_FAILED;
			handler.sendMessage(e1);
		} 
		return res;
	} 
	 
    public void showAlertDialog(final Activity ctx,String message) { 
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx); 
    	builder.setTitle("测试提示");   
    	builder.setMessage(message); 
    	builder.setCancelable(true);
 		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
 			public void onClick(DialogInterface dialog, int id) { 
 				try {
 					Intent intent = new Intent(Intent.ACTION_MAIN);
 					intent.setClassName("com.android.phone", "com.android.phone.NetworkSetting");
 					ctx.startActivity(intent);
 				} catch (Exception e) {
 					showMessage(ctx, "该手机不支持TD/GSM网络切换");
 				}
 			    /*wlanManager.closeWifi();
				wlanManager.setMobileDataEnabled(ctx,true);
				TaskDetailWidget tdw = new TaskDetailWidget(ctx);
 	            ctx.setContentView(tdw);*/
 			}
 		}); 
 		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
 			public void onClick(DialogInterface dialog, int id) { 
        		dialog.cancel();
 			}
 		});
 		wifiListDialog = builder.create();
        wifiListDialog.show();
    }
}
